﻿#region Copyright Notice
// This file is part of GestionPedago.
// <description>
// Copyright (C) 2012 ENI Ecole Informatique
// 
// GestionPedago is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// <program> is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestionPedago.EntityContext;
using System.Data.Objects;
using System.Data;
using Persistence.OPManager;

namespace GestionPedago.Persistence.OPManager
{
    /// <summary>
    /// Manager de persistance de l'objet PlanningECFDetail
    /// </summary>
    public abstract class PlanningECFDetailOPManager
    {
        /// <summary>
        /// Méthode d'ajout d'un PlanningECFDetail en base
        /// </summary>
        /// <param name="ped">L'objet PlanningECFDetail</param>
        /// <param name="idECF">L'id de l'ECF</param>
        /// <param name="fromECFPromotion">La promotion</param>
        /// <returns>L'objet PlanningECFDetail</returns>
        public static PlanningECFDetail AjouterPlanningECFDetail(PlanningECFDetail ped, int idECF, string codePromotion, bool fromECFPromotion = false, bool forceAdd = false)
        {
            try
            {
                
                IQueryable<PlanningECF> query = EntityConnection.GetContext().PlanningECF;
                query = query.Where(it => it.DateECF == ped.PlanningECF.DateECF && it.ECF.IdECF == idECF);
                if(ped.PlanningECF.Promotion != null) {
                    query = query.Where(it => it.CodePromotion == ped.PlanningECF.CodePromotion);
                } else if(codePromotion != null) {
                    if(PromotionOPManager.VerificationCoherenceDateSuggeree(ped.PlanningECF.DateECF, codePromotion, idECF)) {
                        query = query.Where(it => it.CodePromotion == codePromotion);
                    }
                }
                PlanningECF pe = query.FirstOrDefault();
                if (pe == null)
                {
                    DateTime dte = ped.PlanningECF.DateECF;
                    EntityConnection.GetContext().Detach(ped.PlanningECF);
                    //EntityConnection.ClearEntities();
                    PlanningECF peAjout = new PlanningECF();
                    peAjout.IdECF = idECF;
                    peAjout.DateECF = dte;
                    pe = PlanningECFOPManager.AjouterPlanningECF(peAjout);
                }
                else {
                   
                    ped.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(pe.CodePlanningECF);
                    
                    if(!EntityStateChecker.IsDetached(ped.PlanningECF)) {
                        EntityConnection.GetContext().Detach(ped.PlanningECF);
                    }
                    //EntityConnection.ClearEntities();
                }

                if (fromECFPromotion)
                {
                    ped.CodePlanningECF = pe.CodePlanningECF;
                }
                else
                {
                    ped.PlanningECF = pe;
                    if (!EntityStateChecker.IsDetached(ped.PlanningECF))
                    {
                        EntityConnection.GetContext().Detach(ped.PlanningECF);
                    }
                    else
                    {
                        EntityConnection.ClearEntities();
                        ped.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(pe.CodePlanningECF);
                       // ped.PlanningECF.ECF = ECFOPManager.GetECFById(pe.IdECF);
                        EntityConnection.GetContext().Detach(ped.PlanningECF);
                        EntityConnection.GetContext().Detach(ped);
                       
                    }
                }

                if(ped.ContactENI != null && !EntityStateChecker.IsDetached(ped.ContactENI)) {
                    EntityConnection.GetContext().ContactENI.Detach(ped.ContactENI);
                }
                if (ped.PlanningIndividuelFormation != null && 
                        (!EntityStateChecker.IsDetached(ped.PlanningIndividuelFormation) || EntityStateChecker.IsAdded(ped.PlanningIndividuelFormation)))
                {
                    EntityConnection.GetContext().PlanningIndividuelFormation.Detach(ped.PlanningIndividuelFormation);
                }
                if(!EntityStateChecker.IsDetached(pe)) {
                    EntityConnection.GetContext().PlanningECF.Detach(pe);
                }
                if (!EntityStateChecker.IsDetached(ped))
                {
                    EntityConnection.GetContext().PlanningECFDetail.Detach(ped);
                }
              
                EntityConnection.GetContext().PlanningECFDetail.AddObject(ped);
               
                EntityConnection.GetContext().SaveChanges();

                EntityConnection.ClearEntities();

                CreationValidationCompetenceParECFPlanningIndividuelFormation(idECF,ped.CodePlanning);

                return ped;

            }
            catch (Exception ex)
            {

                throw ex;

            }
        }

        /// <summary>
        /// Méthode de récupération d'une liste d'objets PlanningECFDetail par identifiant de planningECF
        /// </summary>
        /// <param name="codePlanningECF">Identifiant du PlanningECF</param>
        /// <returns>L'objet PlanningECFDetail</returns>
        public static List<PlanningECFDetail> GetListePlanningECFDetailByCodePlanningECF(int codePlanningECF)
        {

            IQueryable<PlanningECFDetail> query = EntityConnection.GetContext().PlanningECFDetail;
            query = query.Where(it => it.CodePlanningECF == codePlanningECF);

            List<PlanningECFDetail> lst = query.ToList();            

            return lst;
        }

        /// <summary>
        /// Méthode de récupération d'une liste de PlanningECFDetail par codePlanningIndividuelFormation
        /// </summary>
        /// <param name="codePlanning">L'identifiant du PlanningIndividuelFormation</param>
        /// <returns>La liste d'objets PlanningECFDetail</returns>
        public static List<PlanningECFDetail> GetListePlanningECFDetailByCodePlanningIndividuelFormation(int codePlanning)
        {

            List<PlanningECFDetail> lst = new List<PlanningECFDetail>();

            IQueryable<PlanningECFDetail> query = EntityConnection.GetContext().PlanningECFDetail;
            query = query.Where(it => it.CodePlanning == codePlanning);

            foreach (PlanningECFDetail ped in query)
            {
                lst.Add(ped);
            }

            return lst;
        }

        /// <summary>
        /// Méthode de récupération d'une liste de PlanningECFDetail par codePlanningIndividuelFormation
        /// </summary>
        /// <param name="codePlanning">L'identifiant du PlanningIndividuelFormation</param>
        /// <param name="idECF">L'identifiant de l'ECF</param>
        /// <returns>La liste d'objets PlanningECFDetail</returns>
        public static List<PlanningECFDetail> GetListePlanningECFDetailByCodePlanningIndividuelFormationIdECF(int codePlanning,int idECF)
        {

            List<PlanningECFDetail> lst = new List<PlanningECFDetail>();

            IQueryable<PlanningECFDetail> query = EntityConnection.GetContext().PlanningECFDetail;
            query = query.Where(it => it.CodePlanning == codePlanning && it.PlanningECF.IdECF == idECF);

            foreach (PlanningECFDetail ped in query.ToList())
            {
                lst.Add(ped);
            }
            
            return lst;
        }

        /// <summary>
        /// Méthode de récupération d'un PlanningECFDetail par son id
        /// </summary>
        /// <param name="id">L'identifiant de PlanningECFDetail</param>
        /// <returns>L'objet PlanningECFDetail</returns>
        public static PlanningECFDetail GetPlanningECFDetailById(int id)
        {
            try
            {
                var query = from it in EntityConnection.GetContext().PlanningECFDetail
                            where it.IdPlanningECFDetail == id
                            select it;

                PlanningECFDetail pe = null;

                pe = query.First();

                return pe;

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Méthode de suppression d'un PlanningECFDetail
        /// </summary>
        /// <param name="ped">L'objet PlanningECFDetail à supprimer</param>
        public static void SupprimerPlanningECFDetail(PlanningECFDetail ped)
        {
            try
            {
                /*EntityConnection.GetContext().PlanningECF.Detach(ped.PlanningECF);
                if (ped.ContactENI != null)
                {
                    EntityConnection.GetContext().ContactENI.Detach(ped.ContactENI);
                }*/

                bool horsPromotion = false;
                ped = PlanningECFDetailOPManager.GetPlanningECFDetailById(ped.IdPlanningECFDetail);
                foreach (ValidationCompetence vc in ValidationCompetenceOPManager.GetListeValidationCompetenceByIdPlanningECFDetail(ped.IdPlanningECFDetail))
                {
                   // EntityConnection.GetContext().ValidationCompetence.Detach(vc);
                    ValidationCompetenceOPManager.SupprimerValidationCompetence(vc);
                }
                int codePlanningECF = ped.CodePlanningECF;
                if (ped.PlanningECF.CodePromotion == null)
                {
                    horsPromotion = true;
                }
                EntityConnection.GetContext().PlanningECFDetail.DeleteObject(ped);
                EntityConnection.GetContext().SaveChanges();
                if (horsPromotion)
                {
                    PlanningECFOPManager.SupprimerPlanningECFHorsPromotionIsole(codePlanningECF);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        
        /// <summary>
        /// Méthode de suppression d'un objet PlanningECFDetail 
        /// </summary>
        /// <param name="ped">L'objet PlanningECFDetail à supprimer</param>
        public static void SupprimerPlanningECFDetailFromPlanningECF(PlanningECFDetail ped)
        {
            try
            {
                foreach (ValidationCompetence vc in ValidationCompetenceOPManager.GetListeValidationCompetenceByIdPlanningECFDetail(ped.IdPlanningECFDetail))
                {
                    ValidationCompetenceOPManager.SupprimerValidationCompetence(vc);
                }
                EntityConnection.GetContext().PlanningECFDetail.DeleteObject(ped);
                EntityConnection.GetContext().SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Méthode de mise à jour d'un objet PlanningECFDetail
        /// </summary>
        /// <param name="ped">L'objet PlanningECFDetail</param>
        /// <param name="e">L'ECF</param>
        /// <returns>L'objet PlanningECFDetail</returns>
        public static PlanningECFDetail MiseAJourPlanningECFDetail(PlanningECFDetail ped, ECF e, string codePromotion)
        {
            try
            {
                bool forceAdd = false;
                if (ped.PlanningECF.CodePlanningECF == 0||codePromotion!= null)
                {
                    // EntityConnection.GetContext().Detach(e);
                    IQueryable<PlanningECF> query = EntityConnection.GetContext().PlanningECF;
                    query = query.Where(it => it.DateECF == ped.PlanningECF.DateECF && it.ECF.IdECF ==                             e.IdECF);
                    if(codePromotion != null) {
                         if(PromotionOPManager.VerificationCoherenceDateSuggeree(ped.PlanningECF.DateECF,                               codePromotion, e.IdECF)) {
                            query = query.Where(it => it.CodePromotion == codePromotion);
                         }
                    }
                    PlanningECF pe = query.FirstOrDefault();
                    if (pe == null)
                    {
                        DateTime dte = ped.PlanningECF.DateECF;
                        EntityConnection.ClearEntities();
                        pe = new PlanningECF();
                        pe.DateECF = dte;
                        pe.ECF = ECFOPManager.GetECFById(e.IdECF);
                        pe.IdECF = e.IdECF;
                        pe = PlanningECFOPManager.AjouterPlanningECF(pe);
                        ped.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(pe.CodePlanningECF);
                    }
                    else
                    {
                        
                        if(ped.PlanningECF.IdECF > 0) {
                            forceAdd = true;
                        }
                        ped.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(pe.CodePlanningECF);
                        
                        EntityConnection.ClearEntities();
                        
                       

                    }
                    PlanningECFDetail pedAvantMiseAJour = PlanningECFDetailOPManager.GetPlanningECFDetailById(ped.IdPlanningECFDetail);
                    PlanningECFDetailOPManager.SupprimerPlanningECFDetail(pedAvantMiseAJour);
                    PlanningECFDetail pedMisAJour = new PlanningECFDetail();
                    pedMisAJour.CodeContactENI = ped.CodeContactENI;
                    if (ped.ContactENI != null)
                    {
                        pedMisAJour.ContactENI = ped.ContactENI;
                    }
                    pedMisAJour.IdVersionECF = ped.IdVersionECF;
                    if (ped.VersionECF != null)
                    {
                        pedMisAJour.VersionECF = ped.VersionECF;
                    }
                    pedMisAJour.CodePlanning = ped.CodePlanning;
                    pedMisAJour.CodePlanningECF = ped.CodePlanningECF;
                    if (ped.PlanningECF != null)
                    {
                        pedMisAJour.PlanningECF = ped.PlanningECF;
                    }
                    else
                    {
                        pedMisAJour.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(ped.CodePlanningECF);
                    }
                    if(!EntityStateChecker.IsDetached(ped)) {
                        EntityConnection.GetContext().Detach(ped);
                    }
                    //EntityConnection.GetContext().SaveChanges();
                    //
                    if(forceAdd) {
                        if(!EntityStateChecker.IsDetached(pedMisAJour)) {
                            EntityConnection.GetContext().Detach(pedMisAJour);
                        }
                        ped = PlanningECFDetailOPManager.AjouterPlanningECFDetail(pedMisAJour, e.IdECF, codePromotion);
                    }
                     EntityConnection.ClearEntities();
                     if(!forceAdd) {
                         CreationValidationCompetenceParECFPlanningIndividuelFormation(e.IdECF, ped.CodePlanning);
                     }
                }
                else
                {

                    ped.PlanningECF = PlanningECFOPManager.GetPlanningECFByCode(ped.CodePlanningECF);

                    if (ped.PlanningECF.Promotion != null)
                    {
                        foreach (Cours c in ped.PlanningECF.Promotion.Cours.ToList())
                        {
                            EntityConnection.GetContext().Cours.Detach(c);
                        }
                        EntityConnection.GetContext().Titre.Detach(ped.PlanningECF.Promotion.Formation.Titre);
                        EntityConnection.GetContext().Formation.Detach(ped.PlanningECF.Promotion.Formation);
                        EntityConnection.GetContext().Promotion.Detach(ped.PlanningECF.Promotion);
                    }
                    if(!EntityStateChecker.IsDetached(ped.PlanningECF.ECF)){
                        foreach(VersionECF ve in ped.PlanningECF.ECF.VersionECF.ToList()) {
                            EntityConnection.GetContext().VersionECF.Detach(ve);
                        }
                        EntityConnection.GetContext().ECF.Detach(ped.PlanningECF.ECF);
                        if(ped.PlanningECF.ContactENI != null) {
                            EntityConnection.GetContext().ContactENI.Detach(ped.PlanningECF.ContactENI);
                        }
                    }
                    if(!EntityStateChecker.IsDetached(ped.PlanningECF)){
                        EntityConnection.GetContext().PlanningECF.Detach(ped.PlanningECF);
                    }

                    if (ped.ContactENI != null)
                    {
                        EntityConnection.GetContext().ContactENI.Detach(ped.ContactENI);
                    }
                    if (ped.VersionECF != null)
                    {
                        EntityConnection.GetContext().VersionECF.Detach(ped.VersionECF);
                    }
                    EntityConnection.GetContext().SaveChanges();

                    EntityConnection.ClearEntities();

                }
                
                PlanningECFOPManager.SupprimerTousPlanningECFHorsPromotionIsoles(e.IdECF);
               
                return ped;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void CreationValidationCompetenceParECFPlanningIndividuelFormation(int idECF,int codePlanning)
        {
            List<PlanningECFDetail> lstPedECF = GetListePlanningECFDetailByCodePlanningIndividuelFormationIdECF(codePlanning,idECF);
            foreach (PlanningECFDetail ped in lstPedECF)
            {
                List<CompetenceParECF> listeCpe = CompetenceParECFOPManager.GetListeCompetenceParECFByIdECF(idECF);
                foreach (CompetenceParECF cpe in listeCpe)
                {
                    
                    ValidationCompetence vc = new ValidationCompetence();
                    vc.IdCompetence = cpe.IdCompetence;
                    if(!ValidationCompetenceOPManager.GetListeValidationCompetenceByIdPlanningECFDetail(codePlanning).Contains(vc)) {
                        vc.IdPlanningECFDetail = ped.IdPlanningECFDetail;
                        ValidationCompetenceOPManager.AjouterValidationCompetence(vc);
                    }
                } 
            }

        }
    }
}
